package concurrent;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @ Description：TODO wait notify 生产者消费者模型
 * @ Author：wzj
 * @ Date：2020/7/11 11:47
 */
public class ProducerConsumer {
    public static int cpacity=10;//容量10
    public static Queue<String> queue=new ArrayBlockingQueue<>(cpacity);

    public static void main(String[] args) {
        Producer producer=new Producer();
        Consumer consumer=new Consumer();
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}

class Producer implements Runnable{

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ProducerConsumer.queue.add("商品");
            System.out.println(Thread.currentThread().getName()+" 生产商品");
            if(ProducerConsumer.queue.size()==ProducerConsumer.cpacity){
                System.out.println(Thread.currentThread().getName()+" 生产过多******");
                synchronized (ProducerConsumer.queue){
                    try {
                        ProducerConsumer.queue.wait();//阻塞
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
class Consumer implements Runnable{

    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ProducerConsumer.queue.poll();
            System.out.println(Thread.currentThread().getName()+" 消费商品");
            if(ProducerConsumer.queue.isEmpty()){
                System.out.println(Thread.currentThread().getName()+" 商品没了*******");
                synchronized (ProducerConsumer.queue){
                    ProducerConsumer.queue.notify();//唤醒
                }
            }
        }
    }
}